/**
 * 
 */
package org.swing.utility.common.thread;

import java.util.concurrent.ThreadFactory;

/**
 * @author lqnhu
 *
 */
public class NamingThreadFactory implements ThreadFactory {
	private String name;
	private boolean daemon;
	private Sequencer sequencer;

	/**
	 * Creates a new NamingThreadFactory. All threads will be non-daemon
	 * threads.
	 * 
	 * @param name
	 *            The name (prefix) of any threads created by this factory.
	 */
	public NamingThreadFactory(String name) {
		this(name, false);
	}

	/**
	 * Creates a new NamingThreadFactory.
	 * 
	 * @param name
	 *            The name (prefix) of any threads created by this factory.
	 * @param daemon
	 *            Whether to create a daemon thread.
	 */
	public NamingThreadFactory(String name, boolean daemon) {
		this.name = name;
		this.daemon = daemon;
		this.sequencer = new Sequencer();
	}

	public Thread newThread(Runnable r) {
		long id = sequencer.next();
		String threadName = name + "-" + id;
		Thread thread = new Thread(r, threadName);
		thread.setDaemon(daemon);
		return thread;
	}
}
